package drds.plus.sql_process.abstract_syntax_tree.node.dml;

import drds.plus.sql_process.abstract_syntax_tree.ObjectCreateFactory;
import drds.plus.sql_process.abstract_syntax_tree.execute_plan.dml.IPut;
import drds.plus.sql_process.abstract_syntax_tree.execute_plan.query.Query;
import drds.plus.sql_process.abstract_syntax_tree.node.query.TableQuery;
import drds.plus.sql_process.abstract_syntax_tree.node.query.TableQueryWithIndex;
import drds.plus.sql_process.optimizer.OptimizerContext;
import drds.plus.sql_process.rule.RouteOptimizer;

public class Replace extends Dml<Replace> {

    public Replace(TableQuery tableQueryNode) {
        super(tableQueryNode);
    }

    public IPut toExecutePlan(int shareIndex) {
        drds.plus.sql_process.abstract_syntax_tree.execute_plan.dml.Replace replace = ObjectCreateFactory.createReplace();
        if (this.getWhere().getActualTableName() != null) {
            replace.setTableName(this.getWhere().getActualTableName());
        } else if (this.getWhere() instanceof TableQueryWithIndex) {
            replace.setTableName(((TableQueryWithIndex) this.getWhere()).getIndexName());
        } else {
            replace.setTableName(this.getWhere().getTableName());
        }
        replace.setIndexName(this.getWhere().getIndexMappingUsed().getIndexName());
        replace.setConsistent(true);
        replace.setExistSequenceValue(this.isExistSequenceValue());
        replace.setIsValueListList(this.isValueListList());
        replace.setValueListList(this.getValueListList());
        replace.setUpdateItemList(this.getColumnNameList());
        replace.setUpdateValues(this.getColumnValueList());
        if (this.getQuery() != null) {
            replace.setQueryTree((Query) this.getQuery().toExecutePlan());
        }
        //
        replace.setDataNodeId(this.getWhere().getDataNodeId());
        replace.setBatchIndexList(this.getBatchIndexList());
        return replace;
    }

    public Replace deepCopy() {
        Replace replaceNode = new Replace(null);
        super.deepCopySelfTo(replaceNode);
        return replaceNode;
    }

    public Replace copy() {
        Replace replaceNode = new Replace(null);
        super.copySelfTo(replaceNode);
        return replaceNode;
    }

    public boolean processAutoIncrement() {
        if (!super.processAutoIncrement()) {
            return false;
        }
        String tableName = getTableMetaData().getTableName();
        RouteOptimizer routeOptimizer = OptimizerContext.getOptimizerContext().getRouteOptimizer();
        return !routeOptimizer.isTableInSingleDb(tableName) || routeOptimizer.isBroadCast(tableName);//单库单表才或者广播表才允许自增
    }

}
